package com.want.client.loadbanlance.impl;

import com.want.client.loadbanlance.LoadBalanceSelect;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 轮询的选择器
 *
 * @author WangZhiJian
 * @since 2021/12/19 0019
 */
public class RoundLoadBalanceSelect implements LoadBalanceSelect {

    private AtomicLong index = new AtomicLong();

    @Override
    public ServiceInstance select(final List<ServiceInstance> allServiceList,final Set<ServiceInstance> blackList) {
        if(CollectionUtils.isEmpty(allServiceList))
            throw new RuntimeException("无服务实例存活！");

//        Set<ServiceInstance> tempBlackList = blackList == null ? Collections.emptySet() : blackList;
//        if(tempBlackList.containsAll(allServiceList))
//            throw new RuntimeException("所有服务实例都在黑名单中！");

        long index = this.index.incrementAndGet();
        int serviceIndex = (int) index % allServiceList.size();
        ServiceInstance serviceInstance = allServiceList.get(serviceIndex);

        return serviceInstance;
    }
}
